package com.dylan.structure.queue;

/**
 * @author zhangshaojian
 * @description
 * @date 2022/4/29 16:09
 */
public class SimpleQueue<T> {
    /**
     * 队列容器
     */
    private final Object[] container;
    /**
     * 插入下标前一位
     */
    private int front;
    /**
     * 取出下标前一位
     */
    private int rear;

    public SimpleQueue(Integer maxSize) {
        container = new Object[maxSize];
        front = -1;
        rear = -1;
    }

    public static void main(String[] args) {
        int size = 5;
        SimpleQueue<Integer> queue = new SimpleQueue<>(size);
        for (int i = 0; i < size; i++) {
            queue.put(i);
        }
//        queue.put(6);
        for (int i = 0; i < size; i++) {
            System.out.println(queue.peek());
            System.out.println(queue.take());
        }
        queue.peek();
    }

    public void put(T t) {
        if (isFull()) {
            throw new RuntimeException("容器已满");
        }
        container[++front] = t;
    }

    @SuppressWarnings("unchecked")
    public T take() {
        if (isEmpty()) {
            throw new RuntimeException("容器是空的");
        }
        return (T) container[++rear];
    }

    @SuppressWarnings("unchecked")
    public T peek() {
        if (isEmpty()) {
            throw new RuntimeException("容器是空的");
        }
        return (T) container[rear + 1];
    }

    private boolean isFull() {
        return front + 1 == container.length;
    }

    private boolean isEmpty() {
        return front == rear;
    }
}
